from django.shortcuts import render

# Create your views here.
from django.shortcuts import render

# Create your views here.
from course import models, ser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from django.db.models import Q


class CoursePage(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'size'


class HomeCate(APIView):
    def get(self, request):
        # 展示所有的一级分类的数据  条件 parent=None iddel=False
        allcate = models.Category.objects.filter(parent=None, is_delete=False).order_by("sort")
        # 序列化
        cateser = ser.CategorySer(allcate, many=True)
        data = cateser.data
        for i in data:
            i["children"] = i["children"][:3]
        return Response({"code": 200, "msg": "ok", "data": data})


class ChildCate(APIView):
    def get(self, request):
        id = request.query_params.get("id", "")
        if not id:
            return Response({"code": 400, "msg": "id不能为空"})
        child = models.Category.objects.filter(id=id, is_delete=False).first()
        cateser = ser.CategorySer(child)
        return Response({"code": 200, "msg": "ok", "cate": cateser.data, "course": []})


class Direction(APIView):
    def get(self, request):
        cate = models.Category.objects.filter(parent=None, is_delete=False).order_by("sort")
        cateser = ser.Cate(cate, many=True)
        return Response({"code": 200, "msg": "ok", "data": cateser.data})


class Cate(APIView):
    def get(self, request):
        direction = request.query_params.get("direction", "0")
        if direction == "0":
            child = models.Category.objects.filter(parent__isnull=False, is_delete=False).order_by("sort")
        else:
            child = models.Category.objects.filter(parent_id=direction, is_delete=False).order_by("sort")
        cateser = ser.Cate(child, many=True)
        return Response({"code": 200, "msg": "ok", "data": cateser.data})


class Course(ListAPIView):
    queryset = models.Course.objects.all()
    serializer_class = ser.CourseSer
    pagination_class = CoursePage

    def get_queryset(self):
        query = Q(is_delete=False)
        nav = self.request.query_params.get("nav", "")
        cate = self.request.query_params.get("cate", "")
        direction = self.request.query_params.get("direction", "")
        ordering = self.request.query_params.get("ordering", "")
        if nav:
            query &= Q(nav=nav)
        if cate:
            query &= Q(category=cate)
        if direction and not cate:
            child = models.Category.objects.filter(parent=direction, is_delete=False).values_list("id", flat=True)
            query = query & Q(category__in=child)
        if ordering:
            return self.queryset.filter(query).order_by(ordering)
        else:
            return self.queryset.filter(query)
